package dom4j;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class FirstTest {

	public static void main(String[] args) throws DocumentException, IOException {
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File("1.xml"));
		
		Element root = document.getRootElement();
		Map<String, String> map = parseTomap(root);
		System.out.println(map);
		System.out.println(map.get("Vip"));

		//只能得到直接子节点
		List elements = root.elements("Header");
		System.out.println(elements.size());
		
		//深度查找
		List selectNodes = document.selectNodes("/Envelope/Body/Flight");
		System.out.println(selectNodes.size());
		
		Element element = root.element("Header");
		element.addComment("这是注释");
		Element tuyouElement = element.addElement("tuyou");
		tuyouElement.addAttribute("name", "涂有");
		tuyouElement.addAttribute("age", "23");
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		XMLWriter writer = new XMLWriter(new FileWriter("1.xml"), format);
		writer.write(document);
		writer.close();
	}
	
	public static Map<String, String> parseTomap(Element element){
		
		Map<String, String> map = new HashMap<String, String>();
		map.put(element.getName(), element.getTextTrim());
		if(element.nodeCount() > 0){
			
			for(Iterator i = element.elementIterator(); i.hasNext();){
				
				Element sub = (Element)i.next();
				Map<String, String> subMap = parseTomap(sub);
				map.putAll(subMap);
			}
		}
		return map;
	}
	
	
}
